package com.fangyouyun;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 *  描述：使用SheduledExecutorService时，Runnable内没有捕获的RuntimeException将会使Executor停止运行，并且异常不会被输出。
 *  改正措施：
 *      任务中使用  try{}catch抓取异常
 *
 *
 *   源码可以看出 执行任务均采用：
 *          try{
 *
 *          }finally{
 *
 *          }
 *   结构，故此，不会抛出异常，而导致任务停下
 */
public class ExecutorsPit {
    private static int count = 0;
    public static void main(String[] args){
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try{
                    if(count > 3){
                        throw new RuntimeException("异常.........");
                    }
                }catch (Exception e){
                    System.out.println("异常捕获...........:" + e.getMessage());
                }
                System.out.println("tick........");
                count++;
            }
        }, 0, 3, TimeUnit.SECONDS);
    }


    @Test
    public void updateScheduled() {
        ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    if(count > 3){
                        throw new RuntimeException("异常.........");
                    }
                }catch (Exception e){
                    System.out.println("异常捕获...........:" + e.getMessage());
                }
                System.out.println("tick........");
                count++;
            }
        }, 0, 3, TimeUnit.SECONDS);
    }

}
